import random
import os
import datetime
import time
from pathlib import Path
from rest_framework.response import Response
from django.conf import settings
import re


def img_proccess_save(image, file, imageModel=None):
    # 防重名
    name = Path(image.name)
    img_pure_name = name.stem + '_' + \
        str(int(time.time()))  # name.stem：提取无后缀的文件名
    img_extend_name = name.suffix  # 提取后缀名
    img_name = img_pure_name + img_extend_name  # 新的文件名

    # 创建存储路径
    if imageModel:
        img_upload_to = imageModel.file_path.field.upload_to
    else:
        img_upload_to = 'public_images/'
    temp_dir = os.path.join(settings.MEDIA_ROOT,img_upload_to, file)  # 想要保存的文件夹

    # 递归创建文件夹
    img_dir = ''
    # for path in re.split('\\|\/', temp_dir):
    print('os.sep:', os.sep)
    for path in temp_dir.split('/'):
        if path != '':
            img_dir = os.path.join(img_dir, path)
            if not os.path.exists(img_dir):
                os.mkdir(img_dir)

    # print('img_dir:',img_dir)
    if not os.path.exists(img_dir):
        os.mkdir(img_dir)
    img_file_year = os.path.join(
        img_dir, datetime.datetime.now().strftime("%Y"))  # 按年保存的文件夹
    if not os.path.exists(img_file_year):
        os.mkdir(img_file_year)
    img_file_month = os.path.join(
        img_file_year, datetime.datetime.now().strftime("%m"))  # 按月保存的文件夹
    if not os.path.exists(img_file_month):
        os.mkdir(img_file_month)

    # 存储图片
    destination = open(os.path.join(img_file_month, img_name), 'wb+')
    for chunk in image.chunks():  # 对图片切片
        destination.write(chunk)  # 把切片写入
    destination.close()

    # 传回给后端ImageField要存储的图片路径
    backend_relative_path =img_upload_to + file + '/' + datetime.datetime.now().strftime("%Y") + \
        '/' + datetime.datetime.now().strftime("%m") + '/' + img_name
    print(backend_relative_path)

    return img_name, backend_relative_path

def img_proccess_delete(proxy, instance):
    # 此处可以通过proxy获取到request
    # print(proxy)
    # url_prefix = proxy.request.build_absolute_uri('/')
    # file_path = instance.file_path
    # 方法一, 通过文件路径删除
    # img_path = os.path.join(settings.MEDIA_ROOT, instance.file_path.name)
    # if os.path.exists(img_path):
        # os.remove(img_path)
    # 方法二, 通过django的FileField的delete方法
    img = instance.file_path
    if img:
        img.delete()